package com.sencorsta.ids.proxy;

import com.sencorsta.ids.common.information.ErrorCodeList;
import com.sencorsta.ids.common.proto.PushKickMessage;
import com.sencorsta.ids.common.proto.utils.ReturnUtils;
import com.sencorsta.ids.common.service.MysqlService;
import com.sencorsta.ids.common.service.RedisService;
import com.sencorsta.ids.core.application.Application;
import com.sencorsta.ids.core.application.proxy.ProxyClient;
import com.sencorsta.ids.core.configure.TypeProtocol;
import com.sencorsta.ids.core.configure.TypeSerialize;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.core.tcp.opensocket.OpenServerBootstrap;
import com.sencorsta.ids.core.tcp.opensocket.OpenUser;
import com.sencorsta.ids.core.tcp.socket.protocol.RpcMessage;
import com.sencorsta.utils.date.DateUtil;
import io.netty.channel.Channel;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

public class rpProxy extends Application implements RedisService {

	static {
		instance = new rpProxy();
	}

	public static rpProxy getInstance() {
		return (rpProxy) instance;
	}


	@Override
	public void onOpenClose(Channel channel){//客户端与服务端断连触发
		OpenUser user=channel.attr(OpenServerBootstrap.KEY_OPENUSER).get();
		if (user!=null){
			String userId=user.userId;
			OpenServerBootstrap.getInstance().users.remove(userId);
			R_ROUTE.hremove(user.userId,"proxy");
			String offlineTime = DateUtil.getDateTime();
			R_USER.hset(user.userId, "offlineTime", offlineTime);
			String loginTime = R_USER.hget(user.userId, "loginTime");
			int diffSeconds = DateUtil.getDiffSeconds(loginTime, offlineTime);
			channel.attr(OpenServerBootstrap.getInstance().KEY_OPENUSER).set(null);
			R_USER.hincr(user.userId, "onlineTime", diffSeconds);
			ProxyClient.userLeave(userId,user.serverTypes);

			{//sign是true为新用户----那么这只猪就进来----并且送到mysql的屠宰场杀掉
				Out.debug("------------------------下线数据同步-----------------------------");
				//通过userId得到redis的数据
				Map<String,String> userInfo=R_USER.hgetAll(userId);
				String sql="update `userInfo` set `sex`=?,`nickname`=?,`portrait`=?,`signature`=?,`offlineTime`=? where `userId`=?";

				Object[] args=new Object[]{
						userInfo.get("sex"),userInfo.get("nickname"),userInfo.get("portrait"),userInfo.get("signature"),offlineTime,userInfo.get("userId")
				};
				try {
					MysqlService.getInstance().updateAsyn(sql,args);
				}catch (Exception e){
					Out.debug("新用户信息持久化失败，错误接口：LoginService  当前用户id为"+userId+"需要手动导入");
				}
			}
		}
	}
	private Channel channel;
	@Override
	protected void onCloseGame() {
		Set<String> userIdList=R_ROUTE.keys("*");
		PushKickMessage.PushKick.Builder push=PushKickMessage.PushKick.newBuilder();
		push.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.BOLT_WARNING));
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		try {
			push.build().writeTo(output);
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] byteArray = output.toByteArray();
		RpcMessage puls =null;
		for (var item : userIdList) {
			String SID = R_ROUTE.hget(item,"proxy");
			Out.debug("当前处理-->"+item);
			puls=new RpcMessage();
			puls.header.type = TypeProtocol.TYPE_RPC_RES;
			puls.channel = channel;
			puls.method = "push.Below";
			puls.serializeType = TypeSerialize.TYPE_PROTOBUF;
			puls.data = byteArray;
			puls.userId = item;
			ProxyClient.sendBySID(puls,"proxy" , SID);
			R_ROUTE.del(item);
		}
	}


}
